<template>
  <zm-page>
    <header class="header-opts">
      <input
        type="file"
        id="cropper-input"
        class="cropper-input"
        @change="changeHandler"
      />
      <label for="cropper-input" class="cropper-input-handler van-hairline--bottom">+ 点击选择本地图片</label>
    </header>
    <footer class="footer-opts">
      <van-button type="default"  @click.prevent="$router.go(-1)">取消</van-button>
      <van-button type="primary" :disabled="url===''" @click.prevent="crop">裁切并上传</van-button>
    </footer>
    <zm-body>
      <div class="cropper-box">
        <img
          style="max-width:100%"
          id="image"
          :src="url"
        >
      </div>
    </zm-body>
  </zm-page>
</template>

<script>
/*
  功能描述  上传头像裁切
  创建人    zgf
  更新时间  2019/07/04
  文档地址  
  url参数  
  备注      
*/
import '@/public/load-image/load-image.all.min.js'
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { mapState,mapMutations } from "vuex";
export default {
  name: "UploadCropper",
  data() {
    return {
      headerImage: "",
      picValue: "",
      cropper: null,
      croppable: false,
      url: "",
      acceptTypes:'.jpg,.png,.jpeg,.gif',
      copperImageObj:null
    };
  },
  components: {
    Cropper
  },
  computed: {
    ...mapState(["hasLogin", "userInfo", "userCurRole", "curMode"])
  },
  mounted() {
    this.initCropper();
  },
  methods: {
    ...mapMutations(["login"]),
    initCropper() {
      if (this.cropper) return;
      this.copperImageObj = document.getElementById("image");
      this.cropper = new Cropper(this.copperImageObj, {
        aspectRatio: 1 / 1,
        zoomable: false,
        // checkOrientation:false,
        viewMode:1,
        minCropBoxWidth:150,
        minCropBoxHeight:150,
        rotatable:true,
        scalable:true,
        crop:(event) =>{
          console.log('crop event');
          this.$toast.clear();
        },
        ready: () => {
          this.croppable = true;
        }
      });
    },
    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    checkFile(fileObj){
      if(!fileObj) return false;
      var iType = fileObj.type.split('/')[1];
      console.log(this.acceptTypes.indexOf(iType));
      if(this.acceptTypes.indexOf(iType)===-1){
       ``
        return false;
      }
      return true;
    },
    changeHandler(e) {
      
      let files = e.target.files || e.dataTransfer.files;
      console.log(files[0]);
      this.picValue = files[0];
      let checkRight = this.checkFile(this.picValue);
      if (!files.length) return;
      if(!checkRight) {
        event.target.value = null;
        return;
      };
      ///////////loadimg by js
      // Use the "JavaScript Load Image" functionality to parse the file data
      this.$toast({
        duration:0,
        message:'图片解析中...'
      });
      let options={
        canvas: true
      }
      loadImage.parseMetaData(this.picValue, (data) => {
          if (data.exif) {
              options.orientation = data.exif.get('Orientation');
          }
          loadImage(
              this.picValue,
              (canvas) => {
                var imgDataURL = canvas.toDataURL();
                this.url = imgDataURL;
                //每次替换图片要重新得到新的url
                if (this.cropper) {
                  this.cropper.replace(this.url);
                }
                event.target.value = null;
              },
              options
          );
      });
    },
    crop() {
      var croppedCanvas;
      var roundedCanvas;
      if (!this.croppable) {
        return;
      }
      // Crop
      croppedCanvas = this.cropper.getCroppedCanvas();
      console.log(this.cropper);
      // this.headerImage = roundedCanvas.toDataURL();
      this.changeBase64ToBlob(croppedCanvas);
    },
    changeBase64ToBlob(croppedCanvas) {
      this.$toast.loading({
        mask:true,
        duration:0
      });
      croppedCanvas.toBlob(blob => {
        this.postImg(blob);
      });
    },
    postImg(blob) {
      //这边写图片的上传
      let self = this;
      var fd = new FormData();
      fd.append("upload", 1);
      fd.append("upfile", blob); //file对象
      var uploadUrl =
        this.$config.fileApi +
        "/Files/Upload/Upload.aspx?ID=" +
        this.userInfo.memberid +
        "&token=1&flag=pic&extension=.jpg";
      this.$http({
        method: "POST",
        url: uploadUrl,
        processData: false,
        contentType: false,
        data: fd
      }).then(res => {
        console.log(res);
        if(res && res.headUrl){
          //更新本地和store里的用户头像
          var userInfo = this.$util.deepClone(this.userInfo);
          userInfo.headerpic = this.$config.filePrefix + res.headUrl;
          this.login(userInfo);
          //返回
          this.$router.go(-1);
        }else{
          this.$toast('上传失败，请重试！');
          this.$toast.clear();
        }
      });
    }
  },
  beforeRouteLeave (to, from, next) {
    this.$toast.clear();
    next();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
//引入mixin和var
@import "../../css/mixin.less";
.header-opts {
  position: relative;
  overflow: hidden;
  &:active{
    opacity: 0.05;
  }
  & ~ .zm-body {
    top: 50px;
  }
}
.cropper-input-handler{
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 15px;
  background-color: #fff;
  z-index: 5;
}
.cropper-input{
  // display: none;
  opacity: 0.5;
  font-size: 100px;
  position: absolute;
  right: 0;
  top: 0;
}
.footer-opts {
  position: fixed;
  width: 100%;
  bottom: 0;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  left: 0;
  display: flex;
  z-index: 10;
  button {
    display: block;
    flex: 1;
    border: none;
    height: 50px;
    line-height: 50px;
    font-size: 15px;
    border-radius: 0;
    margin: 0;
    padding: 0;
    &:disabled{
      pointer-events: none;
    }
  }
  & ~ .zm-body {
    bottom: 50px;
  }
}
.cropper-box {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>
